﻿using Kinlo.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using XingLucifer.IBase.Enums;

namespace Kinlo.MESDocking
{
    /// <summary>
    /// 设备在线检测
    /// </summary>
    public class HeartBeat : MESInteractionBase
    {
        public HeartBeat(Action<string, string, string, string, string, long, DateTime, string, string, string> log, Action<string, string, string> dialog)
            : base(log, dialog, "设备在线检测")
        {

        }

        public override ResultTypes Interaction(string url, int timeout, int reconnect_count, DateTime dateTime, ProductionData[] production, Dictionary<string, object> parameters)
        {
            _stopwatch.Restart();
            Dictionary<string, object> para = parameters["parameter"] as Dictionary<string, object>;
            para["Upload_Time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string json = JsonSerializer.Serialize(para, HttpHelper.Options);
            var result = Post(json, url, timeout, reconnect_count);
            _stopwatch.Stop();
            _log?.Invoke("", _name, result.Item1 ? result.Item2 : "请求异常", json, result.Item1 ? result.Item2 : "请求异常",
                _stopwatch.ElapsedMilliseconds, dateTime, parameters["machineNo"].ToString(), parameters["producttype"].ToString(), "heartBeat");
            if (result.Item1)
            {
                Dictionary<string, string> result_json = JsonSerializer.Deserialize<Dictionary<string, string>>(result.Item2, HttpHelper.Options);
                if (result_json["Return_Code"] != "S")
                {
                    string error = string.Empty;
                    switch (result_json["Return_Code"])
                    {
                        case "E0001":
                            error = "上位机软件编号【上位机软件编号】校验失败";
                            break;
                        case "E0002":
                            error = "上位机【上位机软件编号】验证密码校验失败";
                            break;
                        case "E0003":
                            error = "设备编码【设备编码】校验失败";
                            break;
                        case "E0004":
                            error = "上传时间转换失败";
                            break;
                        case "E0101":
                            error = "是否在线字段转换失败";
                            break;
                        case "E":
                            error = "未知异常";
                            break;
                    }
                    _dialog?.Invoke(_name, result_json["Return_Code"], error);
                }
            }
            else
            {
                _dialog?.Invoke(_name, "ERROR", result.Item2);
            }
            return result.Item1 ? ResultTypes.合格 : ResultTypes.MES_NG;
        }
    }
}
